import { Order } from '../order/order-model.js';
import { Cart } from '../cart/cart-model.js';
import { Address } from '../../utils/address.js';


var order = new Order();
var cart = new Cart();
var address = new Address();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fromCartFlag: true,
    addressInfo: null,
    hiddenBox: true,
    all_buy_total: 0,
    amount: 0
  },

  onLoad: function (options) {
    var flag = options.from && options.from;
    var cartId = options.id && options.id;
    this.data.flag = flag;
    this.data.cartId = cartId;
    if (flag == 'cart' || flag == 'buy') {//购物车或者直接购买时
      this.setData({
        orderStatus: 0
      })
    }
    if (flag == "cart") {
      this.data.type = 0;
    } else if (flag == "buy") {
      this.data.type = 1;
    }

    this._loadData(flag);
  },

  _loadData: function (flag) {
    /*通过接口获取用户默认的收货地址*/

    address.getAddress((res) => {
      var params = {};
      if (res.status == 1) {
        var addressInfo = {
          id: res.items.id,
          name: res.items.userName,
          mobile: res.items.telNumber,
          totalDetail: address.setAddressInfo(res.items)
        };
        this.setData({
          addressInfo: addressInfo
        });
        console.log()
        params = { "type": 0, "address_id": res.items.id };
        if (flag == 'buy') {
          params = { "type": 1, "address_id": res.items.id, "id": this.data.cartId }
        }
      } else if (res.status == 0) {
        params = { "type": 0 };
        if (flag == 'buy') {
          params = { "type": 1, "id": this.data.cartId }
        }
      }

      order.getOrdersToPay(params, (data) => { //获取购物车选定的商品信息（价格、数量、总价）
        this.data.amount = data.amount;
        var itemList = data.items;
        var orderDatas = [];
        for (let i in itemList) {
          orderDatas.push(itemList[i]);
        }
        orderDatas = this._getCaculateShopTotal(orderDatas)
        this.setData({
          orderTOPayData: orderDatas,
          amount: this.data.amount,
          scoreMoney: data.scoreMoney,
          all_buy_total: data.buy_total
        })
      })

    });

  },
  /*修改或者添加地址信息*/
  editAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        if (res.telNumber) {
          //保存地址
          address.submitAddress(res, (data) => {
            var addressInfo = {
              id: data.items.id,
              name: res.userName,
              mobile: res.telNumber,
              totalDetail: address.setAddressInfo(res)
            };
            that.setData({
              addressInfo: addressInfo
            });
          });
        }
      }
    })
  },

  //积分开关改变
  jifenSwitchChange: function (e) {
    var status = e.detail.value;
    this.data.status = status;
    this._getCaculateAmount(status);
  },

  // 合计
  _getCaculateAmount: function (status) {
    if (status) {
      this.data.amount = parseFloat(this.data.amount).toFixed(2) - parseFloat(this.data.scoreMoney).toFixed(2);

    } else {
      this.data.amount = (parseFloat(this.data.amount).toFixed(2) * 100 + parseFloat(this.data.scoreMoney).toFixed(2) * 100) / 100;
    }
    this.setData({
      amount: this.data.amount
    })
  },

  // 小计
  _getCaculateShopTotal: function (orderDatas) {
    var len = orderDatas.length,
      total = 0;
    for (let i = 0; i < len; i++) {
      if (orderDatas[i].shipping_price == null) {
        orderDatas[i].shipping_price = 0;
      }

      total = parseFloat(orderDatas[i].sale_real_total).toFixed(2) * 100 + parseFloat(orderDatas[i].shipping_price).toFixed(2) * 100;
      orderDatas[i].shopTotal = total / 100;
    }
    return orderDatas;
  },









  pay: function () {
    if (!this.data.addressInfo) {
      wx.showToast({
        title: '请填写您的收货地址~',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (this.data.orderStatus == 0) {
      this._firstTimePay();
    } else {
      // this._oneMoresTimePay();
    }

  },

  /*第一次支付*/
  _firstTimePay: function () {
    var shops = [];
    var message = this.data.inputVal ? this.data.inputVal : '';
    var orderTOPayData = this.data.orderTOPayData;
    var len = orderTOPayData.length;
    for (let i = 0; i < len; i++) {
      var childLen = orderTOPayData[i].data.length;
      var cart_ids = [];
      for (let j = 0; j < childLen; j++) {
        cart_ids.push(parseInt(orderTOPayData[i].data[j].id));
      }
      var obj = {
        'id': orderTOPayData[i].shop.id,
        'cart_ids': cart_ids,
        'discount': 0,
        'shipping_price': orderTOPayData[i].shipping_price,
        'mark': message,
        'buy_total': orderTOPayData[i].buy_total,
        'amount': this.data.amount
      };
      shops.push(obj);
    }
    var scoreMoney = 0;
    if (this.data.status) {
      scoreMoney = this.data.scoreMoney;
    }
    var params = {
      'shops': shops,
      'type': this.data.type,
      'scoreMoney': scoreMoney,
      'aid': this.data.addressInfo.id,
      'real_amount': this.data.amount,
      'mark': message,
    }

    var that = this;
    //支付分两步，第一步是生成订单号，然后根据订单号支付
    order.doOrder(params, (data) => {
      //订单生成成功

      if (data.status == 1) {
        //更新订单状态
        that.data.fromCartFlag = false;
        //开始支付
        var params = { 'parent_id': data.msg }
        that._execPay(params);
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
        // that._orderFail(data);  // 下单失败
      }
    });

  },
  _execPay: function (params) {
    var that = this;
    order.execPay(params, (data) => {
      if (data.is_cash == 0) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(function () {
              wx.navigateTo({
                url: '../order/list?index=0'
              });
            }, 2000)
          }
        })
      } else if (data == 1 || data == 2) {
        console.log(111);
        wx.navigateTo({
          url: '../order/list?index=0'
        });
      }

    });
  },

  // 获取留言信息
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },

})